import express, { Request, Response, NextFunction, ErrorRequestHandler } from 'express';
import { config } from './config';
import { AppDataSource } from './config/database';
import authRouter from './api/auth.route';
import cors from 'cors';
import cron from 'node-cron';
import { refreshAllTokens } from './tasks/tokenRefresher';
import path from "path";
import deviceRoute from "./api/device.route";
import notifyRouter from './api/notify.route';
import sseRoute from "./api/sse.route";
import bodyParser from 'body-parser';
import sensorRoute from "./api/sensor.route";


const app = express();

// 添加 JSON 解析中间件
app.use(bodyParser.json());

// 初始化数据库连接
AppDataSource.initialize().then(() => {
    console.log('数据库连接成功');
}).catch((error) => {
    console.error('数据库连接失败:', error);
    throw error;
  });

// 配置中间件
app.use(express.json());
app.use(cors()); // 跨域支持
// 本地互联测试
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:9000'); // 客户端地址
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});
// 设置静态文件目录（存放 CSS、JS 等资源）
const publicPath = path.join(__dirname, 'public');
app.use(express.static(publicPath));


// 测试路由
app.get('/', (req, res) => {
  res.send('Auth service running.');
});

// 授权路由
 app.use('/auth', authRouter);
// 设备路由
app.use('/device', deviceRoute);
// 第三方消息接收
app.use('/api', notifyRouter);
// sse
app.use('/', sseRoute);
// 传感器
app.use('/api', sensorRoute);



// 启动服务器
app.listen(config.port, () => {
  console.log(`Server listening on port ${config.port}`);
});


// 每日凌晨2点刷新一次现有token
cron.schedule('0 2 * * *', async () => {
   console.log('[CRON] start refresh all the access_tokens');
   await refreshAllTokens();
});

// 全局错误处理中间件
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error(err.stack); // 将错误堆栈信息输出到控制台
  res.status(500).json({
    status: 'error',
    message: 'Internal server error'
  });
})












